package com.fjzn.detect.core.utils.sign;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

public class JWTUtils {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer ";

    private static final String SECRET = "jwtsecretdemo";
    private static final String Key = "hwaepjv1qxjtwqpz";

    public static final long EXPIRATION = 7*24*3600;


    public static String createToken(String id) {
        String encryId = AESUtils.encryptBase64(id,Key);
        return Jwts.builder()
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .setId(encryId)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION * 1000))
                .compact();
    }

    public static String getId(String token){
        String rs = "";
        try {
            Claims claims = getTokenBody(token);
            if(claims != null){
                rs = AESUtils.decryptBase64(claims.getId(),Key);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  rs;
    }

    public static Claims getTokenBody(String token){
        try{
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        }catch(Exception e){

        }
        return null;
    }

    public static void main(String[] args){
        String token = createToken("123");
        System.out.println(token);
        System.out.println(getId(token));
    }


}
